<template>
  <j-modal
    :title="title"
    :width="isBatch ? 1000 : 800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :destroyOnClose="true"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!-- 单个物料模式 -->
        <template v-if="!isBatch">
          <!-- 物料基本信息 -->
          <a-card :bordered="false" title="物料基本信息" style="margin-bottom: 16px">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="物料编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input :value="materialCode" disabled />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="物料名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input :value="materialName" disabled />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="物料类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tag v-if="materialType" :color="
                    materialType == '1' ? 'blue' : 
                    materialType == '2' ? 'green' : 
                    materialType == '3' ? 'orange' : 
                    materialType == '4' ? 'purple' : 
                    materialType == '5' ? 'red' : 
                    materialType == '6' ? 'yellow' : ''"
                  >
                    {{ 
                      materialType == '1' ? '型材' : 
                      materialType == '2' ? '配件' : 
                      materialType == '3' ? '辅件' : 
                      materialType == '4' ? '其他' : 
                      materialType == '5' ? '余料' : 
                      materialType == '6' ? '半料' : '-'
                    }}
                  </a-tag>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="规格型号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input :value="specification" disabled />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input :value="supplierName" disabled />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="不合格数量" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input :value="unqualifiedQuantity + ' ' + unit" disabled />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
          
          <!-- 退货/换货信息 -->
          <a-card :bordered="false" :title="type === 1 ? '退货信息' : '换货信息'">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  :label="type === 1 ? '退货数量' : '换货数量'"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-input-number
                    v-decorator="[
                      'quantity',
                      {
                        initialValue: unqualifiedQuantity,
                        rules: [
                          { required: true, message: '请输入数量' },
                          { validator: validateQuantity }
                        ]
                      }
                    ]"
                    :min="1"
                    :max="unqualifiedQuantity"
                    :precision="2"
                    style="width: 100%"
                    disabled
                    @change="calculateAmount"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input :value="unit" disabled />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="单价(元)" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number
                    v-decorator="[
                      'unitPrice',
                      {
                        initialValue: unitPrice,
                        rules: [{ required: true, message: '请输入单价' }]
                      }
                    ]"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                    disabled
                    @change="calculateAmount"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="金额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number
                    v-decorator="[
                      'totalAmount',
                      {
                        initialValue: totalAmount
                      }
                    ]"
                    :precision="2"
                    style="width: 100%"
                    disabled
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item
                  :label="type === 1 ? '退货原因' : '换货原因'"
                  :labelCol="{ span: 4 }"
                  :wrapperCol="{ span: 20 }"
                >
                  <a-textarea
                    v-decorator="[
                      'reason',
                      {
                        rules: [{ required: true, message: '请输入原因' }]
                      }
                    ]"
                    :rows="4"
                    placeholder="请输入原因"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item
                  label="凭证"
                  :labelCol="{ span: 4 }"
                  :wrapperCol="{ span: 20 }"
                >
                  <j-image-upload
                    v-decorator="[
                      'evidence',
                      {
                        rules: [{ required: false }]
                      }
                    ]"
                    :number="3"
                    :isMultiple="true"
                    bizPath="purchase/returnExchange"
                    :returnUrl="true"
                    accept=".jpg,.jpeg,.png,.gif"
                    :beforeUpload="beforeUpload"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </template>
        
        <!-- 批量处理模式 -->
        <template v-else>
          <!-- 批量物料列表 -->
          <a-card :bordered="false" :title="type === 1 ? '批量退货物料列表' : '批量换货物料列表'" style="margin-bottom: 16px">
            <a-table
              size="middle"
              bordered
              rowKey="inspectionId"
              :columns="batchColumns"
              :dataSource="batchItems"
              :pagination="false"
              :scroll="{ x: 1200 }"
            >
              <!-- 物料类型列 -->
              <template slot="materialTypeSlot" slot-scope="text">
                <a-tag v-if="text" :color="
                  text == '1' ? 'blue' : 
                  text == '2' ? 'green' : 
                  text == '3' ? 'orange' : 
                  text == '4' ? 'purple' : 
                  text == '5' ? 'red' : 
                  text == '6' ? 'yellow' : ''"
                >
                  {{ 
                    text == '1' ? '型材' : 
                    text == '2' ? '配件' : 
                    text == '3' ? '辅件' : 
                    text == '4' ? '其他' : 
                    text == '5' ? '余料' : 
                    text == '6' ? '半料' : '-'
                  }}
                </a-tag>
              </template>
            </a-table>
          </a-card>
          
          <!-- 批量退货/换货信息 -->
          <a-card :bordered="false" :title="type === 1 ? '批量退货信息' : '批量换货信息'">
            <a-row :gutter="24">
              <a-col :span="24">
                <a-alert
                  :message="`您选择了 ${batchItems.length} 项物料进行${typeText}操作`"
                  type="info"
                  show-icon
                  style="margin-bottom: 16px"
                />
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item
                  :label="type === 1 ? '退货原因' : '换货原因'"
                  :labelCol="{ span: 4 }"
                  :wrapperCol="{ span: 20 }"
                >
                  <a-textarea
                    v-decorator="[
                      'batchReason',
                      {
                        rules: [{ required: true, message: '请输入原因' }]
                      }
                    ]"
                    :rows="4"
                    placeholder="请输入原因"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item
                  label="凭证"
                  :labelCol="{ span: 4 }"
                  :wrapperCol="{ span: 20 }"
                >
                  <j-image-upload
                    v-decorator="[
                      'batchEvidence',
                      {
                        rules: [{ required: false }]
                      }
                    ]"
                    :number="3"
                    :isMultiple="true"
                    bizPath="purchase/returnExchange"
                    :returnUrl="true"
                    accept=".jpg,.jpeg,.png,.gif"
                    :beforeUpload="beforeUpload"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </template>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import { postAction } from '@/api/manage'
import JImageUpload from '@/components/jeecg/JImageUpload'

export default {
  name: 'PurchaseReturnExchangeModal',
  components: {
    JImageUpload
  },
  data() {
    return {
      title: '退货/换货',
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      
      // 物料基本信息
      purchaseOrderId: '',
      purchaseOrderNo: '',
      inspectionId: '',
      materialId: '',
      materialCode: '',
      materialName: '',
      materialType: '',
      specification: '',
      unit: '',
      unqualifiedQuantity: 0,
      unitPrice: 0,
      totalAmount: 0,
      supplierId: '',
      supplierName: '',
      
      // 退货/换货类型：1-退货，2-换货
      type: 1,
      
      // 批量处理相关
      isBatch: false,
      batchItems: [],
      batchColumns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '物料编码',
          align: "center",
          dataIndex: 'materialCode',
          width: 120
        },
        {
          title: '物料名称',
          align: "center",
          dataIndex: 'materialName',
          width: 150
        },
        {
          title: '物料类型',
          align: "center",
          dataIndex: 'materialType',
          width: 100,
          scopedSlots: { customRender: 'materialTypeSlot' }
        },
        {
          title: '规格型号',
          align: "center",
          dataIndex: 'specification',
          width: 120
        },
        {
          title: '不合格数量',
          align: "center",
          dataIndex: 'unqualifiedQuantity',
          width: 100
        },
        {
          title: '单位',
          align: "center",
          dataIndex: 'unit',
          width: 100
        }
      ],
      
      // API URL
      url: {
        createReturn: '/wms/purchase/returnExchange/createReturn',
        createExchange: '/wms/purchase/returnExchange/createExchange',
        batchCreateReturn: '/wms/purchase/returnExchange/batchCreateReturn',
        batchCreateExchange: '/wms/purchase/returnExchange/batchCreateExchange'
      }
    }
  },
  computed: {
    typeText() {
      return this.type === 1 ? '退货' : '换货'
    }
  },
  methods: {
    // 显示单个退换货模态框
    show(record) {
      this.visible = true
      this.isBatch = false
      
      // 设置物料基本信息
      this.purchaseOrderId = record.purchaseOrderId
      this.purchaseOrderNo = record.purchaseOrderNo
      this.inspectionId = record.inspectionId
      this.materialId = record.materialId
      this.materialCode = record.materialCode
      this.materialName = record.materialName
      this.materialType = record.materialType
      this.specification = record.specification
      this.unit = record.unit
      this.unqualifiedQuantity = record.unqualifiedQuantity
      this.unitPrice = record.unitPrice || 0
      this.totalAmount = this.unqualifiedQuantity * this.unitPrice
      this.supplierId = record.supplierId
      this.supplierName = record.supplierName
      
      // 设置类型
      this.type = record.type
      this.title = this.type === 1 ? '退货' : '换货'
      
      // 重置表单
      this.form.resetFields()
    },
    
    // 显示批量退换货模态框
    showBatch(batchData) {
      this.visible = true
      this.isBatch = true
      
      // 设置采购单信息
      this.purchaseOrderId = batchData.purchaseOrderId
      this.purchaseOrderNo = batchData.purchaseOrderNo
      
      // 设置类型
      this.type = batchData.type
      this.title = this.type === 1 ? '批量退货' : '批量换货'
      
      // 设置批量物料项
      this.batchItems = batchData.items
      
      // 重置表单
      this.form.resetFields()
    },
    
    handleCancel() {
      this.visible = false
      this.isBatch = false
      this.batchItems = []
    },
    
    handleOk() {
      // 区分单个和批量处理
      if (this.isBatch) {
        this.handleBatchOk()
      } else {
        this.handleSingleOk()
      }
    },
    
    // 处理单个退换货提交
    handleSingleOk() {
      this.form.validateFields(['quantity', 'unitPrice', 'totalAmount', 'reason', 'evidence'], (err, values) => {
        if (err) return
        
        this.confirmLoading = true
        
        // 构建提交数据
        const params = {
          purchaseOrderId: this.purchaseOrderId,
          purchaseOrderNo: this.purchaseOrderNo,
          inspectionId: this.inspectionId,
          materialId: this.materialId,
          materialCode: this.materialCode,
          materialName: this.materialName,
          materialType: this.materialType,
          specification: this.specification,
          unit: this.unit,
          quantity: values.quantity,
          unitPrice: values.unitPrice,
          totalAmount: values.totalAmount,
          reason: values.reason,
          evidence: values.evidence,
          supplierId: this.supplierId,
          supplierName: this.supplierName
        }
        
        // 生成退换货单号
        const prefix = this.type === 1 ? 'TH' : 'HH';
        params.returnExchangeNo = `${this.purchaseOrderNo}-${prefix}`;
        
        // 根据类型选择API
        const url = this.type === 1 ? this.url.createReturn : this.url.createExchange
        
        // 提交请求
        postAction(url, params).then(res => {
          if (res.success) {
            this.$message.success(res.message || `${this.typeText}记录创建成功`)
            this.visible = false
            this.$emit('ok')
          } else {
            this.$message.error(res.message || `${this.typeText}记录创建失败`)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      })
    },
    
    // 处理批量退换货提交
    handleBatchOk() {
      this.form.validateFields(['batchReason', 'batchEvidence'], (err, values) => {
        if (err) return
        
        this.confirmLoading = true
        
        // 生成退换货单号
        const prefix = this.type === 1 ? 'TH' : 'HH';
        const returnExchangeNo = `${this.purchaseOrderNo}-${prefix}`;
        
        // 构建提交数据
        const params = {
          purchaseOrderId: this.purchaseOrderId,
          purchaseOrderNo: this.purchaseOrderNo,
          reason: values.batchReason,
          evidence: values.batchEvidence,
          returnExchangeNo: returnExchangeNo,
          items: this.batchItems.map(item => {
            // 计算每个物料的总金额
            const quantity = item.unqualifiedQuantity;
            const unitPrice = item.unitPrice || 0;
            const totalAmount = quantity * unitPrice;
            
            return {
              inspectionId: item.inspectionId,
              materialId: item.materialId,
              materialCode: item.materialCode,
              materialName: item.materialName,
              materialType: item.materialType,
              specification: item.specification,
              unit: item.unit,
              quantity: item.unqualifiedQuantity, // 默认使用全部不合格数量
              unitPrice: unitPrice,
              totalAmount: totalAmount,
              supplierId: item.supplierId,
              supplierName: item.supplierName
            }
          })
        }
        
        // 根据类型选择API
        const url = this.type === 1 ? this.url.batchCreateReturn : this.url.batchCreateExchange
        
        // 提交请求
        postAction(url, params).then(res => {
          if (res.success) {
            this.$message.success(res.message || `批量${this.typeText}记录创建成功`)
            this.visible = false
            this.$emit('ok')
          } else {
            this.$message.error(res.message || `批量${this.typeText}记录创建失败`)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      })
    },
    
    // 验证数量
    validateQuantity(rule, value, callback) {
      if (value > this.unqualifiedQuantity) {
        callback(`${this.typeText}数量不能超过不合格数量`)
      } else {
        callback()
      }
    },
    
    // 计算金额
    calculateAmount() {
      const quantity = this.form.getFieldValue('quantity')
      const unitPrice = this.form.getFieldValue('unitPrice')
      this.totalAmount = quantity * unitPrice
      this.form.setFieldsValue({ totalAmount: this.totalAmount })
    },
    
    // 验证上传文件类型
    beforeUpload(file) {
      const isImage = file.type.indexOf('image/') === 0
      if (!isImage) {
        this.$message.error('只能上传图片格式文件!')
      }
      return isImage
    }
  }
}
</script>

<style scoped>
.material-thumbnail {
  max-width: 100%;
  max-height: 80px;
  cursor: pointer;
}
</style> 